import { Col, Empty, Form, Spin, Tabs } from 'antd';
import React, { useContext, useMemo, useRef, useState } from 'react';
import { ContractCountPaymentRight } from './ContractCountPaymentRight';
import { ContractHomeContext } from '../../../common';
import { reportAllByDateStepService } from '../services';
import { ContractCountPaymentLeftHeard } from './ContractCountPaymentLeftHeard';
import pageStyles from '@/common/pageLayout.less';
import ReactDOM from 'react-dom';
import Cls from 'classnames';
import * as echarts from 'echarts';
import { useEchartsData } from '../mconfig/useEchartsData';
import _ from 'lodash';
import { IContractHPActionEnum } from '../../../common/useReducer';

export const ContractCountPayment: React.FC = () => {
  /**引入上下文 */
  const { styleFixCls, curRes, dispatch } = useContext(ContractHomeContext);
  /** 空 */
  const [isShowEm, setIsShowEm] = useState<boolean>(false);
  /**回调函数 */
  const countCallback = (res: any) => {
    if (res?.msgFlag) {
      const result = useEchartsData(res?.obj, '0');
      renderLineChart(result);
      if (result?.length) {
        setIsShowEm(false);
        renderLineChart(result);
      } else {
        setIsShowEm(true);
      }
      dispatch({ type: IContractHPActionEnum.set_copeWithData, payload: result });
    }
  };

  /** 折线图Ref */
  let receivableRef: any = useRef();

  //引入统计接口
  const { reportAllByDateStepLoading, reportAllByDateStepRun } = reportAllByDateStepService(curRes, countCallback);

  /** 刷新 */
  const tabsExtraBtns = () => {
    return <ContractCountPaymentLeftHeard reportAllByDateStepRun={reportAllByDateStepRun} />;
  };

  /**
   * 处理柱状图鼠标移入气泡
   * @param params
   * @returns
   */
  const renderTooltip = (params: Record<string, any>[], data) => {
    let tipStr: string = `${params?.[0]?.name}`;
    const resObj = data?.find((item) => item?.name == tipStr);
    params?.forEach((item) => {
      tipStr += ` 
            <br />
            <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#fc8251;"></span>实付金额 : ${resObj?.totalPaid}元
            <br />
            <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#ccc;"></span>未付金额 : ${resObj?.totalResidue}元
            <br />
            ${params?.[0]?.marker}应付金额 : ${resObj?.totalSum}元
            `;
    });
    return tipStr;
  };

  /** 渲染折线图 */
  const renderLineChart = (data) => {
    if (receivableRef?.current) {
      const putStateViewDiv: any = ReactDOM.findDOMNode(receivableRef?.current);
      const myChart = echarts.init(putStateViewDiv);
      // let maxObj = getMaxObj(data);
      const option = {
        // title: {
        //   text: `${maxObj?.name}月应付金额最高 ${maxObj?.totalSum} 元`,
        //   left: 'left',
        //   textStyle: {
        //     fontSize: 18,
        //   },
        // },
        xAxis: {
          type: 'category',
          data: data?.map((item) => item?.name),
        },
        yAxis: { type: 'value' },
        // legend: {
        // data: ['实付金额', '未付金额', '应付金额'],
        //   padding: [30, 5],
        // },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
          formatter: (params) => {
            return renderTooltip(params, data);
          },
        },
        series: [
          {
            name: '总金额',
            data: data?.map((item) => item?.totalSum),
            type: 'line',
          },
        ],
      };
      myChart.setOption(option as any);
    }
  };

  /** tab配置 */
  const tabsItem = useMemo(() => {
    return [
      {
        label: '全年应付金额',
        key: '1',
        children: isShowEm ? (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ) : (
          <div className={`${styleFixCls}RootDiv-echartBoxDiv`} ref={receivableRef} style={{ height: '100%', width: '100%' }}></div>
        ),
      },
    ];
  }, [curRes, receivableRef, isShowEm]);

  return (
    <>
      <Col span={16} className={styleFixCls + 'RootDiv-ColSpanB'}>
        <Spin spinning={reportAllByDateStepLoading}>
          <div className={Cls(pageStyles['commonTabsLine'])} style={{ height: '100%', width: '100%' }}>
            <Tabs tabBarExtraContent={tabsExtraBtns()} items={tabsItem} />
          </div>
        </Spin>
      </Col>

      <ContractCountPaymentRight countLoading={reportAllByDateStepLoading} />
    </>
  );
};
